import { Component, OnInit } from '@angular/core';
import { StoreService } from '../store.service';
import { DataService } from '../data.service';
import { VisualService } from '../visual.service';
import fileSaver from 'file-saver';
import { json2csv } from 'json-2-csv';
@Component({
  selector: 'app-query',
  templateUrl: './query.component.html',
  styleUrls: ['./query.component.less'],
})
export class QueryComponent implements OnInit {
  constructor(
    public storeService: StoreService,
    public dataService: DataService,
    public visualService: VisualService
  ) {}

  ngOnInit() {}
  queryString: string = '';
  docqueryString: string = 'input query string for doc';
  current: any;

  totalpage = 100;
  currentpage = 1;
  countperpage = 10;
  prePage = 3;
  nextPage = 3;
  pages: number[] = [];
  async search() {
    this.currentpage = 1;
    let r = await this.dataService.query(
      'mr/',
      this.queryString,
      1,
      this.countperpage
    );

    let ro = JSON.parse(r as string);

    this.storeService.results = ro['body']['results'];
    this.totalpage = this.storeService.results.length;
    this.pages.splice(0, this.pages.length);
    for (
      let i = 1;
      i < Math.min(...[this.totalpage, this.currentpage + this.nextPage]);
      i++
    )
      this.pages.push(i);
  }
  async pagesearch(page) {
    this.currentpage = page;
    let r = await this.dataService.query(
      'mr/',
      this.queryString,
      page,
      this.countperpage
    );

    let ro = JSON.parse(r as string);
    this.storeService.results = ro['body']['results'];
    this.pages.splice(0, this.pages.length);
    for (
      let i = Math.max(...[1, this.currentpage - this.prePage]);
      i < this.currentpage;
      i++
    )
      this.pages.push(i);

    for (
      let i = this.currentpage;
      i <= Math.min(...[this.totalpage, this.currentpage + this.nextPage]);
      i++
    )
      this.pages.push(i);
  }
  export() {
    if (this.storeService.results.length > 0) {
      //let converter = require('json-2-csv');
      //let ts = JSON.stringify(this.storeService.results)
      json2csv(this.storeService.results, (err, csv) => {
        if (err) throw err;

        let blob = new Blob([csv], {
          type: 'text/plain;charset=utf-8',
        });
        fileSaver.saveAs(blob, 'result.search.csv');
      });
    }
  }
}
